/**
 * Created by shenc on 2015/12/8.
 */

//购物车列表js
var opts = {
    viewBox: ".js-viewBox",
    jqP: "#listSelect",
    listEl: ".list-item",
    toolEl: ".js-tools",
    url: page_global.del_url,
    callBacks: {
        oneSelCb: function (listItem, isSel, id) {
            getCartData();
        },
        allSelCb: function (listItems, isSel, ids) {
            getCartData();
        },
        delCb: function (listItem, id) {
            getCartData();
        }
    }
};
var newList = new ListSelect(opts);

//修改商品数量
$('.num-tool').each(function () {
    numPlugin($(this), function (val, numInput) {
        getCartData(val, numInput);
    });
});

//滚动页面浮动列表底部
var listFoot=$('#listFooter'),tableItem=$('.list-foot',listFoot),winH=$(window).height();
$(window).on('scroll',function(){
   var scrollTop=$('body').scrollTop(),
       footOffset=listFoot.offset();
    winH=$(window).height();
    tableItem.toggleClass('fix-foot',footOffset.top-scrollTop>winH-56);
}).trigger('scroll');


var paymentBtn = $('.js-payment'),
    isCancel=false;

//结算
paymentBtn.on('click', function (e) {
    var that = $(this), defTxt = that.text();
    var url = that.attr('url');
    if (that.hasClass('disabled') || that.prop('disabled')) return false;

    if(newList.viewBoxEl.hasClass('cart-danger')){
        that.addClass('disabled').prop('disabled',true);
        tools.goToY($('#js-focusOn').offset().top,100);
        return false;
    }

/*
    var warningItem=newList.viewBoxEl.find('.inner-tj.waring');
    if(warningItem.length&&!that.hasClass('go-on')){
        tools.goToY(warningItem.eq(0).offset().top-100,200,function(){
            that.addClass('go-on');
        });
        layer.tips('关税已超出50元！只有小于等于50元时才能免征哦 ', '.inner-tj.waring .skin-warning .gs',{
            tips:[3,'#ff7800'],
            area: '300px',
            time:4000
        });
        that.text('继续结算');
        return false;
    }
*/

    var goods_list = newList.getSelectLi();
    var cartGoods = getGoodsData(goods_list);
    if (cartGoods.length == 0) return false;

    that.addClass('disabled').prop('disabled', true).text('结算中...');
    $.ajax({
        url: page_global.settlement_url,
        type: 'post',
        dataType: 'json',
        data: {"cartGoods": cartGoods},
        success: function (res) {
            if (res.status == 'success') {
                window.location.href = '/order';
            } else {

                //todo 有错误时展示错误
            }

        },
        error: function () {

        }
    }).done(function () {
        setTimeout(function () {
            that.removeClass('disabled').prop('disabled', false).text(defTxt);
        }, 1000);
    });

});

function getCartData(val, numInput) {
    var selectLi, id;

    var totalPay = newList.toolEl.find('.js-totalPay'),
        totalGs = newList.toolEl.find('.js-totalGs'),
        totalNum = newList.toolEl.find('.js-totalNum');

    if (val) {
        var $el = numInput.closest('.list-item'),
            price = $el.data('price'),
            tariff = $el.data('tariff'),
            chkItem = $('.js-checkbox', $el),
            singlePay = $('.js-singlePay', $el),
            singleGs = $('.js-singleGs', $el);

        id = $el.data('id');

        //修改数字时，默认选中商品
        $el.data('num', val);
        $el.addClass('cur');

        //设置单个商品的总价/关税
        singlePay.text((val * 1 * price).toFixed(2));
        singleGs.text((val * 1 * price * tariff / 100).toFixed(2));

        if (!chkItem.prop('checked')) {
            chkItem.click();
            return false;
        }
    }

    selectLi = newList.getSelectLi();
    var cartGoods = getGoodsData(selectLi);

    paymentBtn.removeClass('go-on').text('结 算');

    if (cartGoods.length == 0) {
        //全部取消选中时，不请求，直接修改统计值为0
        totalPay.text('0.00');
        totalGs.text('0.00');
        totalNum.text(0);

        //隐藏所有警告
        newList.viewBoxEl.find('.cart-danger').removeClass('cart-danger');
        //newList.viewBoxEl.find('.inner-tj.waring').removeClass('waring');

        //禁用提交按钮
        paymentBtn.addClass('disabled').prop('disabled',true);

        //单笔非单个商品 超过1000元，禁止购买
        newList.viewBoxEl.removeClass('cart-danger');

        //设置购物车状态
        isCancel=true;
        return false;
    }
    isCancel=false;

    id = id || cartGoods[0].goods_id;

    $.ajax({
        url: page_global.edit_url + '/' + id,
        data: {"cartGoods": cartGoods},
        dataType: 'json',
        type: 'post',
        success: function (res) {
            tools.log(res);
            if(isCancel) return false;

            //出错处理
            //{message: "该商品库存不足",status: 402}
            if(res.message){
                return false;
            }

            //设置总关税、价格、数量
            if(res.info){
                totalPay.text(res.info.pay_price);
                totalGs.text(res.info.total_tariff_price);
                totalNum.text(res.info.total_number);

                //设置E贸易商品关税、总价1000提示
                var eShopGoods=res.info.eshopGoods;

                if(eShopGoods.total_number>0){

                    //根据返回数据设置E贸易商品的统计信息和提示信息
                    checkCart(eShopGoods);

                }else{

                    //若E贸易商品没有一个选中，则返回信息中没有E贸易商品
                    var shopTable=$('#eShopTable');
                    shopTable.removeClass('cart-danger');
                    shopTable.find('.waring').removeClass('waring');
                }

                //最后，设置支付按钮状态
                if(newList.viewBoxEl.hasClass('cart-danger')){
                    paymentBtn.addClass('disabled').prop('disabled',true);
                }else{
                    paymentBtn.removeClass('disabled').prop('disabled',false);
                }

            }
        }
    });
}

function checkCart(shopInfo){
    var shopTable=$('#eShopTable'),
        shopENum=shopInfo.total_price,
        disNum=shopInfo.total_discount_price,
        shopGoodsNum=shopInfo.total_number;

    shopTable.toggleClass('cart-danger',(shopENum*1-disNum*1)>=1000&&shopGoodsNum>1);

}

//生成已选择商品数据
function getGoodsData(lis) {
    var data = [];

    if (typeof lis != 'undefined' && lis.length) {

        for (var i = 0; i < lis.length; i++) {
            var curLi = lis.eq(i);

            data.push({goods_id: curLi.data('id'), buy_num: curLi.data('num')});
        }

    }

    return data;
}